class Boxes extends egret.Sprite {
    private box: Box
    private boxes: Array<Box>
    private gravity: number = 0.2

    public constructor() {
        super()
        this.once(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage(): void {
        this.boxes = new Array<Box>()
        this.createBox()
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(): void {
        this.box.vy += this.gravity
        this.box.y += this.box.vy

        for (let i = 0; i < this.boxes.length; ++i) {
            if (this.box != this.boxes[i] && this.hitTest(this.box, this.boxes[i])) {
                this.box.y = this.boxes[i].y - this.boxes[i].height / 2 - this.box.height / 2
                this.createBox()
                return
            }
        }

        if (this.box.y + this.box.height / 2 > this.stage.stageHeight) {
            this.box.y = this.stage.stageHeight - this.box.height / 2
            this.createBox()
        }
    }

    private createBox() {
        this.box = new Box(Math.random() * 40 + 10, Math.random() * 40 + 10)
        this.box.x = Math.random() * this.stage.stageWidth
        this.addChild(this.box)
        this.boxes.push(this.box)
    }

    private hitTest(obj1: egret.DisplayObject, obj2: egret.DisplayObject): boolean {
        var rect1: egret.Rectangle = obj1.getBounds()
        var rect2: egret.Rectangle = obj2.getBounds()
        rect1.x = obj1.x
        rect1.y = obj1.y
        rect2.x = obj2.x
        rect2.y = obj2.y
        return rect1.intersects(rect2)
    }
}